package com.ruoyi.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.domain.AppTeamList;
import com.ruoyi.app.domain.AppTeamVideo;
import com.ruoyi.app.domain.bo.*;
import com.ruoyi.app.domain.vo.*;
import com.ruoyi.app.mapper.AppTeamListMapper;
import com.ruoyi.app.service.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.CommentType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DistanceUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * APP用户动态Service业务层处理
 *
 * @author heike
 * @date 2023-08-17
 */
@RequiredArgsConstructor
@Service
public class AppTeamListServiceImpl implements IAppTeamListService {

    private final AppTeamListMapper baseMapper;
    private final IAppUserService appUserService;
    private final IAppTeamLikeService appTeamLikeService;
    private final IAppTeamTypeService appTeamTypeService;
    private final IAppTeamApplyService appTeamApplyService;
    private final IAppTeamVideoService appTeamVideoService;
    private final IAppTeamCommentService appTeamCommentService;
    private final IAppUserSettingService appUserSettingService;
    private final IAppTeamEvaluateService appTeamEvaluateService;


    /**
     * 查询APP用户动态
     */
    @Override
    public AppTeamListVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询APP用户动态列表
     */
    @Override
    public TableDataInfo<AppTeamListVo> queryPageList(AppTeamListBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppTeamList> lqw = buildQueryWrapper(bo);
        Page<AppTeamListVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询APP用户动态列表
     */
    @Override
    public List<AppTeamListVo> queryList(AppTeamListBo bo) {
        LambdaQueryWrapper<AppTeamList> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<AppTeamListVo> queryList(Long userId, List<String> status) {
        LambdaQueryWrapper<AppTeamList> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppTeamList::getUserId,userId).in(AppTeamList::getStatus, status);
        return baseMapper.selectVoList(wrapper);
    }

    @Override
    public AppTeamListVo queryByGroup(String groupId) {
        LambdaQueryWrapper<AppTeamList> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppTeamList::getGroupId, groupId);
        return baseMapper.selectVoOne(wrapper);
    }

    private LambdaQueryWrapper<AppTeamList> buildQueryWrapper(AppTeamListBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppTeamList> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), AppTeamList::getTitle, bo.getTitle());
        lqw.eq(bo.getUserId() != null, AppTeamList::getUserId, bo.getUserId());
        lqw.eq(bo.getTeamType() != null, AppTeamList::getTeamType, bo.getTeamType());
        lqw.eq(bo.getType() != null, AppTeamList::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), AppTeamList::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getSexNeed()), AppTeamList::getSexNeed, bo.getSexNeed());
        lqw.eq(StringUtils.isNotBlank(bo.getCost()), AppTeamList::getCost, bo.getCost());
        lqw.eq(bo.getNumber() != null, AppTeamList::getNumber, bo.getNumber());
        return lqw;
    }

    /**
     * 新增APP用户动态
     */
    @Override
    public Boolean insertByBo(AppTeamListBo bo) {
        AppTeamList add = BeanUtil.toBean(bo, AppTeamList.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 新增APP用户动态
     */
    @Override
    public Boolean insert(AppTeamList appTeamList) {
        AppTeamList add = BeanUtil.toBean(appTeamList, AppTeamList.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            appTeamList.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改APP用户动态
     */
    @Override
    public Boolean updateByVo(AppTeamListVo vo) {
        AppTeamList update = BeanUtil.toBean(vo, AppTeamList.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 修改APP用户动态
     */
    @Override
    public Boolean updateByBo(AppTeamListBo bo) {
        AppTeamList update = BeanUtil.toBean(bo, AppTeamList.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppTeamList entity) {
        //TODO 做一些数据校验,如唯一约束
    }


    /**
     * 批量删除APP用户动态
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean addTeam(AppTeamListBo bo) {
        if (insertByBo(bo)) {
            if (bo.getHeight() != null && bo.getWidth() != null) {
                String[] height = bo.getHeight().split(",");
                String[] width = bo.getWidth().split(",");
                for (int i = 0; i < bo.getImagesList().size(); i++) {
                    String e = bo.getImagesList().get(i);
                    AppTeamVideo video = new AppTeamVideo();
                    video.setImage(e);
                    video.setTeamId(bo.getId());
                    video.setHeight(Integer.valueOf(height[i]));
                    video.setWidth(Integer.valueOf(width[i]));
                    video.setSmallImage(e);
                    appTeamVideoService.insert(video);
                }
            }
            return true;
        }
        return false;
    }

    @Override
    public TableDataInfo<AppTeamListVo> queryDate(TableDataInfo<AppTeamListVo> page, Long userId
    ) {
        for (AppTeamListVo e : page.getData()) {
            info(e, userId);
        }
        return page;
    }

    @Override
    public List<AppTeamListVo> queryDate(List<AppTeamListVo> list, Long userId) {
        for (AppTeamListVo e : list) {
            info(e, userId);
        }
        return list;
    }

    @Override
    public HashMap<String, String> like(Long id, Long userId, String type) {
        AppTeamLikeVo appTeamLikeVo = appTeamLikeService.queryByTeamIdAndUserId(id, userId, type);
        HashMap<String, String> hashMap = new HashMap<>();
        if (Objects.isNull(appTeamLikeVo)) {
            AppTeamLikeBo appTeamLikeBo = new AppTeamLikeBo();
            appTeamLikeBo.setLikeId(id);
            appTeamLikeBo.setUserId(userId);
            appTeamLikeBo.setType(type);
            appTeamLikeService.insertByBo(appTeamLikeBo);
            hashMap.put("msg", "点赞成功");
            hashMap.put("sign", "OK");
            hashMap.put("status", "0");
        } else {
            appTeamLikeService.delect(appTeamLikeVo.getId());
            hashMap.put("msg", "取消点赞成功");
            hashMap.put("sign", "CANCEL");
            hashMap.put("status", "1");
        }
        return hashMap;
    }

    @Override
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    /**
     * 处理动态信息
     *
     * @param e  动态信息
     * @param id 用户ID
     * @return
     */
    private AppTeamListVo infoBack(AppTeamListVo e, Long id) {
        //报名用户列表
        AppTeamApplyBo team = new AppTeamApplyBo();
        team.setTeamId(e.getId());
        team.setStatus(Constants.SUCCESS);
        List<AppTeamApplyVo> appTeamApplyVos = appTeamApplyService.queryList(team);
        e.setApplicantNumber(appTeamApplyVos.size());
        AppTeamApplyBo teamApplyBo = new AppTeamApplyBo();
        teamApplyBo.setTeamId(e.getId());
        List<AppTeamApplyVo> teamApplies = appTeamApplyService.queryList(teamApplyBo);
        teamApplies.forEach(k -> {
            AppUserVo appUserVo = appUserService.queryById(k.getUserId());
            k.setAvatar(appUserVo.getAvatar());
        });
        e.setAppTeamApplies(teamApplies);
        //我是否报名
        e.setIsJoin(appTeamApplyService.join(e.getId(), id));
        //我是否已经评价
        e.setIsEvaluate(Objects.nonNull(appTeamEvaluateService.queryUser(e.getId(), id)));
        //点赞人列表点赞数量
        List<AppTeamLikeVo> likeVos = appTeamLikeService.queryByLike(e.getId(), CommentType.DYNAMIC.getCode());
        if (!likeVos.isEmpty()) {
            likeVos.forEach(i -> i.setUserVo(appUserService.userVo(i.getUserId())));
        }
        e.setLikeVos(likeVos);
        e.setLikeVosNumber(likeVos.size());
        e.setCostName(appTeamTypeService.costName(e.getCost()));
        //当前用户是否点赞
        e.setUserLike(appTeamLikeService.queryByUser(e.getId(), id, CommentType.DYNAMIC.getCode()));
        //评论信息
        AppTeamCommentBo commentBo = new AppTeamCommentBo();
        commentBo.setTeamId(e.getId());
        List<AppTeamCommentVo> commentVos = appTeamCommentService.queryList(commentBo);
        if (!commentVos.isEmpty()) {
            e.setCommentVosNumber(commentVos.size());
            commentVos.forEach(c -> {
                c.setUserVo(appUserService.queryById(c.getUserId()));
                List<AppTeamLikeVo> commentLikes = appTeamLikeService.queryByLike(c.getId(), CommentType.COMMENT.getCode());
                if (!commentLikes.isEmpty()) {
                    c.setCommentLikeVosNumber(commentLikes.size());
                }
                c.setUserCommentLike(appTeamLikeService.queryByUser(c.getId(), id, CommentType.COMMENT.getCode()));
                c.setCreateTimeFormat(DateUtils.getDatePoorSingle(c.getCreateTime()));
            });
            e.setCommentVos(commentVos);
        } else {
            e.setCommentVos(commentVos);
            e.setCommentVosNumber(0);
        }
        //发布动态用户信息
        UserVo userVo = appUserService.queryByIdUserVo(e.getUserId());
        e.setUserVo(userVo);
        //任务图片
        AppTeamVideoBo appTeamVideoBo = new AppTeamVideoBo();
        appTeamVideoBo.setTeamId(e.getId());
        List<AppTeamVideoVo> videoVos = appTeamVideoService.queryList(appTeamVideoBo);
        e.setVideoVos(videoVos);
        String createTimeFormat = DateUtils.getDatePoorSingle(e.getCreateTime());
        if (createTimeFormat == null) {
            createTimeFormat = Constants.JUST;
        }
        e.setCreateTimeFormat(createTimeFormat);
        //分类信息
        AppTeamTypeVo appTeamTypeVo = appTeamTypeService.queryById(e.getTeamType());
        e.setTeamTypeName(appTeamTypeVo.getName());
        e.setTypeName(appTeamTypeService.getInfo(e.getType()).getName());
        e.setTeamTotalType(appTeamTypeService.getInfo(e.getType()));
        //距离信息
        e.setDistance(null);
        e.setDistanceText(null);
        AppUserSettingVo nowUser = appUserSettingService.queryByUserId(id);
        if (
            !id.equals(e.getUserId())
                && nowUser.getLatitude() != null
                && nowUser.getLongitude() != null
                && e.getLatitude() != null
                && e.getLongitude() != null
        ) {
            int distance = (int) Math.round(DistanceUtils.getDistances(nowUser.getLongitude(), nowUser.getLatitude(), e.getLongitude().doubleValue(), e.getLatitude().doubleValue()));
            if (distance < 1000) {
                e.setDistance(1);
                if (distance == 0) {
                    e.setDistanceText("10m");
                } else {
                    e.setDistanceText(distance + "m");
                }
            } else {
                e.setDistance(distance / 1000);
                BigDecimal kilometer = new BigDecimal(distance).divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP);
                if (kilometer.compareTo(new BigDecimal("100")) >= 0) {
                    e.setDistanceText("100km以上");
                } else {
                    e.setDistanceText(kilometer + "km");
                }
            }
        }
        return e;
    }


    private AppTeamListVo info(AppTeamListVo e, Long id) {
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd HH:mm");
        e.setStartTimFormat(sdf.format(new Date(e.getStartTime()*1000L)));
        e.setEndTimeFormat(sdf.format(new Date(e.getEndTime()*1000L)));
        //任务图片
        if(StringUtils.isNotBlank(e.getImages())){
            String[] split = e.getImages().split(",");
            e.setTeamImages(Arrays.stream(split).filter(StringUtils::isNotBlank).collect(Collectors.toList()));
        }
        String createTimeFormat = DateUtils.getDatePoorSingle(e.getCreateTime());
        if (createTimeFormat == null) {
            createTimeFormat = Constants.JUST;
        }
        e.setCreateTimeFormat(createTimeFormat);
        return e;
    }



    @Override
    public AppTeamListVo queryInfo(AppTeamListVo appTeamListVo, Long id) {
        return info(appTeamListVo, id);
    }
}
